/*
 * @lc app=leetcode.cn id=61 lang=java
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    /**
     * Accepted
    231/231 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 62.63 % of java submissions (40.9 MB)
     */
    public ListNode rotateRight(ListNode head, int k) {
        ListNode cur = head, last = head;
        int len = 0;
        while (cur != null) {
            len++;
            if (cur.next == null) {
                last = cur;
            }
            cur = cur.next;
        }
        if (len <= 1)
            return head;
        int pos = k % len;
        if (pos == 0)
            return head;

        cur = head;
        pos = len - pos;
        for (int i = 1; i < pos; i++) {
            cur = cur.next;
        }
        ListNode result = cur.next;
        cur.next = null;
        last.next = head;
        return result;
    }
}
// @lc code=end
